<template>
  <div class="bom-container">
    <BasicInformation
      title="BOM管理"
      :primary-actions="actions"
      @action="handleAction"
    />

    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <!-- 基础信息 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>

        <el-row :gutter="30">
          <el-col :md="12">
            <el-form-item label="BOM名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入BOM名称"
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :md="12">
            <el-form-item label="主产品" prop="product">
              <good-selector v-model="form.product" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 原材料管理 -->
      <el-card class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">原材料清单</span>
            <el-button
              type="primary"
              size="small"
              @click="materialDialogVisible = true"
            >
              添加原材料
            </el-button>
          </div>
        </template>

        <el-table :data="form.material" border style="width: 100%">
          <el-table-column prop="code" label="物料编码" />
          <el-table-column prop="name" label="物料名称" />
          <el-table-column prop="kname" label="物料种类" />
          <el-table-column prop="uname" label="物料单位" />
          <el-table-column prop="tax" label="税率" />
        </el-table>
      </el-card>

      <!-- 物料选择对话框 -->
      <material-selector-dialog
        v-model:modelValue="form.material"
        v-model:visible="materialDialogVisible"
      />
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { BOM, Good } from '@/types/basic/BOM'
import BasicInformation from '@/public-view/BasicInformation.vue'
import GoodSelector from '@/basic-view/bom/GoodSelector.vue'
import MaterialSelectorDialog from '@/basic-view/bom/MaterialSelectorDialog.vue'
import request from '@/util/request'

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

// 表单数据
const form = reactive<BOM>({
  id: 0,
  name: '',
  product: null,
  materials: [],
  createUser: user.user.name,
  updateUser: user.user.name,
})

// 验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入BOM名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  product: [
    { required: true, message: '请选择主产品', trigger: 'change' }
  ]
})

// 弹窗控制
const materialDialogVisible = ref(false)

// 操作按钮
const actions = [
  { name: 'save', label: '保存BOM', type: 'primary' },
  { name: 'reset', label: '重置表单', type: 'warning' }
]

// 监听产品变化（选填）
watch(
  () => form.product,
  (newVal, oldVal) => {
    console.log('产品变化：', newVal, oldVal)
  },
  { deep: true }
)

// 表单引用
const formRef = ref<FormInstance>()

// 操作处理
function handleAction(action: string) {
  if (action === 'save') submitForm()
  else if (action === 'reset') resetForm()
}

// 提交表单到后端
async function submitForm() {
  try {
    await formRef.value?.validate()
    const payload: BOM = {
      ...form,
      material: form.material.map(m => ({
        id:   m.id,
        code: m.code,
        name: m.name,
        kid:  m.kid,
        uid:  m.uid,
        tax:  m.tax
      }))
    }
    console.log('发送 BOM 数据：', payload)
    const resp = await request.post('basic/BOM/addBOM', payload)
    console.log(resp.data)
    if (resp.data.code == 200) {
      ElMessage.success(resp.data.message || 'BOM 添加成功')
    } else {
      ElMessage.error(resp.data.message || 'BOM 添加失败')
    }
  } catch (err: any) {
    console.error('提交失败：', err)
    ElMessage.error('网络或服务异常，BOM 保存失败')
  }
}

function resetForm() {
  formRef.value?.resetFields()
  form.material = []
  ElMessage.info('已重置表单')
}
</script>

<style scoped>
.bom-container { padding: 20px; }
.form-section { margin-bottom: 20px; }
.section-header { display: flex; justify-content: space-between; align-items: center; }
.section-title { font-size: 16px; font-weight: 600; }
</style>
